package com.pug.service.message;

import com.pug.dto.MessageDto;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.AbstractJavaTypeMapper;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * Author: lqm
 * create: 2022/4/5 16:54
 * Lover: lqx
 *
 * @see
 */
@Service
public class MessageServiceMq {
    public static final String message_direct_queue="message_direct_queue";
    public static final String message_direct_exchange="message_direct_exchange";
    public static final String message_direct_key="message_direct_key";
    @Resource
    RabbitTemplate rabbitTemplate;
    public void pushMessageSave(MessageDto messageDto){
        //设置编码
        rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
        rabbitTemplate.setExchange(message_direct_exchange);
        rabbitTemplate.setRoutingKey(message_direct_key);
        rabbitTemplate.convertAndSend(messageDto, new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                MessageProperties messageProperties = message.getMessageProperties();
                //设置头信息 表示以MessageDto对象传过去
                messageProperties.setHeader(AbstractJavaTypeMapper.DEFAULT_CONTENT_CLASSID_FIELD_NAME,MessageDto.class);
                //设置持久化
                messageProperties.setDeliveryMode(MessageDeliveryMode.PERSISTENT);
                return message;
            }
        });
    }
}
